import os
from enum import Enum

from django.conf import settings
from django.http import JsonResponse, HttpResponse, FileResponse
from rest_framework.views import APIView
from django.conf import settings
from app01.models import Contract, FeeStandard, FeeType
from app01.models import ContractType
from app01.models import ContractStatus
from app01.Baseview import BasedAPIView
from datetime import datetime, date
from django.utils import timezone
from django.db.models import Q
from app01.woutils.user_jwt import ParseToekn

from enum import Enum


class Contract_Api(BasedAPIView):
    def get(self, request, *args, **kwargs):
        module = kwargs.get('module')
        if module == 'get_page_all':
            return self.get_page_all(request)
        if module == 'get_pdf':
            return self.get_pdf(request)

    def post(self, request, *args, **kwargs):
        module = kwargs.get('module')
        if module == 'add':
            return self.add(request)
        if module == 'edit':
            return self.edit(request)
        if module == 'dele':
            return self.dele(request)

    def get_page_all(self, request):
        try:
            page = int(request.GET.get("page", 1))
            pagesize = int(request.GET.get("pagesize", 10))
        except Exception as e:
            page = 1
            pagesize = 10
        if page < 1:
            page = 1
        query = Q()
        title = request.GET.get("title", "")
        name = request.GET.get("name", "")
        status = request.GET.get("status", "")
        if title:
            query &= Q(title__contains=title)
        if name:
            query &= Q(name__contains=name)
        if status:
            query &= Q(status=status)

        datas = Contract.objects.filter(query).order_by("-id")
        data_list = []
        today = date.today()

        for item in datas:
            try:
                # 根据当前合同的用户来获取其水费标准
                water_fee = FeeStandard.objects.get(user=item.id, fee_type=FeeType.WATER.value)
                electricity_fee = FeeStandard.objects.get(user=item.id, fee_type=FeeType.ELECTRICITY.value)
                property_management_fee = FeeStandard.objects.get(user=item.id, fee_type=FeeType.PROPERTY_MANAGEMENT.value)
            except FeeStandard.DoesNotExist:
                water_fee_value = 0
                electricity_fee_value = 0
                property_management_fee_value = 0

            remaining_days = None
            if item.end_date and item.end_date > today:
                remaining_days = (item.end_date - today).days
            data = {
                "id": item.id,
                "name": item.name,
                "title": item.title,
                "status": item.status.status,
                "contract_type": item.contract_type.name,
                "start_date": item.start_date.strftime("%Y-%m-%d"),
                "end_date": item.end_date.strftime("%Y-%m-%d"),
                "file_name": item.file_name,
                "mid": item.mid,
                "path": item.path,
                "remaining_days": remaining_days,
                "description": item.description,
            }
            data_list.append(data)

        start_page = page * pagesize - pagesize
        end_page = page * pagesize
        paginated_data = data_list[start_page:end_page]
        res_data = {
            "data": paginated_data,
            "total": datas.count(),
        }
        return super().success(data=res_data)

    def get_pdf(self, request):
        contract_id = request.GET.get("id")
        if not contract_id:
            return JsonResponse({"error": "Missing contract_id parameter"})

        try:
            contract = Contract.objects.get(id=contract_id)
        except Contract.DoesNotExist:
            return JsonResponse({"error": "Contract not found"})

        pdf_relative_path = contract.pdf_file.name if contract.pdf_file else None
        if not pdf_relative_path:
            return JsonResponse({"error": "No PDF file associated with this contract"})

        pdf_full_path = os.path.join(settings.MEDIA_ROOT, pdf_relative_path)
        print(pdf_relative_path)
        if not os.path.exists(pdf_full_path):
            return JsonResponse({"error": "PDF file not found"})

        try:
            response = FileResponse(open(pdf_full_path, 'rb'), content_type='application/pdf')
            response['Content-Disposition'] = f'inline; filename="{contract.title}.pdf"'
            return response
        except Exception as e:
            return JsonResponse({"error": "Error serving the PDF file"})
